<?php

namespace StudyBuddy;

/**
 * Class to format time difference
 * (From php comments page
 * http://us.php.net/manual/en/dateinterval.format.php)
 *
 * Usage example:
 * TimeAgo::format(new DateTime('Sat, 22 Jan 2011 21:19:03 -0600')
 * will return formatted string like 10 days and 5 hours ago
 * Notice we don't pass $end param in the example, so
 * current time is used instead
 *
 *
 */
class TimeAgo {

    public static function format(\DateTime $start, \DateTime $end = null) {

        $end = (!$end) ? new \DateTime() : $end;

        $interval = $end->diff($start);
        $doPlural = function($nb, $str) {
                    return $nb > 1 ? $str . 's' : $str;
                }; // adds plurals

        $format = array();
        if ($interval->y !== 0) {
            $format[] = "%y " . $doPlural($interval->y, "year");
        }
        if ($interval->m !== 0) {
            $format[] = "%m " . $doPlural($interval->m, "month");
        }
        if ($interval->d !== 0) {
            $format[] = "%d " . $doPlural($interval->d, "day");
        }
        if ($interval->h !== 0) {
            $format[] = "%h " . $doPlural($interval->h, "hour");
        }
        if ($interval->i !== 0) {
            $format[] = "%i " . $doPlural($interval->i, "minute");
        }
        if ($interval->s !== 0) {
            if (!count($format)) {
                return "less than a minute ago";
            } else {
                $format[] = "%s " . $doPlural($interval->s, "second");
            }
        }

        // We use the two biggest parts
        if (count($format) > 1) {
            $format = array_shift($format) . " and " . array_shift($format) . ' ago';
        } else {
            $format = array_pop($format) . ' ago';
        }

        return $interval->format($format);
    }

}
